package com.leyou.cart.sevice;

import com.leyou.auth.pojo.UserInfo;
import com.leyou.cart.client.GoodsClient;
import com.leyou.cart.interceptor.LoginInterceptor;
import com.leyou.cart.pojo.Cart;
import com.leyou.item.pojo.Sku;
import com.leyou.utils.JsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description:
 * @author: Mr_Sun
 * @Date: 2018/9/26
 * @Time: 14:47
 */
@Service
public class CartService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private GoodsClient goodsClient;
    private static final String key_prefix="leyou:cart";
    public void addCart(Cart cart) {
        //获取用户信息
        UserInfo userInfo = LoginInterceptor.get();
        //处理key
        String key = key_prefix + userInfo.getId();
        //查询用户购物信息 String对应的是userId  第一个Object对应的是skuId 第二个对应的是 Object 是cart对象
        BoundHashOperations<String, Object, Object> hashOperations = this.redisTemplate.boundHashOps(key);
        //取出前台页面传过来的数量
        Integer num = cart.getNum();
        //如果原来的redis中有  更新数量
        if (hashOperations.hasKey(cart.getSkuId().toString())) {//这里的hasKey对应的是第一个object 即把第一个object作为key
            String cartJason = hashOperations.get(cart.getSkuId().toString()).toString();
            //反序列化
             cart = JsonUtils.parse(cartJason, Cart.class);
             cart.setNum(num+cart.getNum());

        } else {
            //无  新增购物车
            Sku sku = this.goodsClient.querySkuBySkuId(cart.getSkuId());
            cart.setUserId(userInfo.getId());
            cart.setTitle(sku.getTitle());
            cart.setOwnSpec(sku.getOwnSpec());
            cart.setImage(StringUtils.isBlank(sku.getImages()) ? "":StringUtils.split(sku.getImages(),",")[0]);
            cart.setPrice(sku.getPrice());

        }
        //更新redis购物车
        hashOperations.put(cart.getSkuId().toString(),JsonUtils.serialize(cart));

    }

    public List<Cart> queryCarts() {
        UserInfo userInfo = LoginInterceptor.get();
        String key = key_prefix + userInfo.getId();
        BoundHashOperations<String, Object, Object> boundHashOperations = this.redisTemplate.boundHashOps(key);
        //获取购物车字符串集合
        List<Object> cartJasons = boundHashOperations.values();
        //如果为购物车字符串集合为空  直接返回null
        if (CollectionUtils.isEmpty(cartJasons)) {
            return null;
        }
        //把一个 List<Object>转换成  List<Cart>
        return cartJasons.stream().map(cartJason -> JsonUtils.parse(cartJason.toString(), Cart.class)).collect(Collectors.toList());
    }
}
